const { default: classNames } = require('classnames')
const _ = require('../utils')
const { listItemBehavior, listParentBehavior } = require('../behaviors')

_.create('slider', {
  options: {
    multipleSlots: true,
  },

  data: {
    handlerSize: 28,
    position: 0,
  },

  properties: {
    label: String,
    type: {
      type: String,
      value: 'primary',
    },
    min: {
      type: Number,
      value: 0,
    },
    max: {
      type: Number,
      value: 100,
    },
    step: {
      type: Number,
      value: 1,
    },
    disabled: Boolean,
    showValue: Boolean,
  },

  behaviors: ['wx://form-field', listItemBehavior],

  relations: {
    listParent: {
      type: 'child',
      target: listParentBehavior,
    },
  },

  computed: {
    classes(data) {
      const { classPrefix, disabled, type, hover, showValue } = data
      const classes = classNames(classPrefix, `${classPrefix}-${type}`, {
        [`${classPrefix}-disabled`]: disabled,
        [`${classPrefix}-hover`]: hover,
        [`${classPrefix}-show-value`]: showValue,
      })

      return classes
    },

    values(data) {
      const { min, max, step } = data
      const arr = []

      for (let index = min; index <= max; index += step) {
        arr.push(index)
      }

      return arr
    },
  },

  observers: {
    value: function (v) {
      const { max, min, containerWidth, handlerSize } = this.data
      const position = ((v - min) / (max - min)) * (containerWidth - handlerSize)
      this.setData({ position })
    },
  },

  lifetimes: {
    attached() {
      const that = this
      const query = this.createSelectorQuery()
      query
        .select('#container')
        .boundingClientRect(function (res) {
          that.setData({
            containerWidth: res.width,
          })
        })
        .exec()
    },
  },

  methods: {
    _setValue(x) {
      const { max, min, handlerSize, containerWidth, values, disabled } = this.data
      if (disabled) return

      const search = (x / (containerWidth - handlerSize)) * (max - min) + min
      let closest = Math.min()
      let value = 0

      values.forEach((item) => {
        const abs = Math.abs(search - item)
        if (closest > abs) {
          closest = abs
          value = item
        }
      })

      this.setData({ value })
    },

    onTouchStart() {
      if (this.data.disabled) return
      this.setData({ hover: true })
    },

    onTouchEnd() {
      if (this.data.disabled) return
      this.setData({ hover: false })
    },

    onChange(e) {
      const { x, source } = e.detail

      if (!source) return
      this._setValue(x)
    },

    onTap(e) {
      const { x } = e.detail
      this._setValue(x - this.data.handlerSize)
    },
  },
})
